package com.smartao.core.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.web.filter.GenericFilterBean;

import com.smartao.core.security.AuthenticationToken;

public class SessionContextFilter extends GenericFilterBean {

	private static final String JSESSIONID = "jsessionid";
	
	private final Logger logger = LoggerFactory.getLogger(SessionContextFilter.class);

	private SessionRegistry sessionRegistry;

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		String jsessionid = request.getParameter(JSESSIONID);
		try{
			SessionInformation sessionInformation = sessionRegistry.getSessionInformation(jsessionid);
			AuthenticationToken token = (AuthenticationToken) sessionInformation.getPrincipal();
			SecurityContextHolder.getContext().setAuthentication(token);
		}catch (Exception e) {
			logger.info("Session not fond: {}",jsessionid);
		}

		chain.doFilter(request, response);
	}

	public void setSessionRegistry(SessionRegistry sessionRegistry) {
		this.sessionRegistry = sessionRegistry;
	}

}
